package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService{
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;


    @Override
    public PageResult getItemList(PageResult pageResult) {
        //回传5个参数 total/分页后的数据
        IPage iPage = new Page(pageResult.getPageNum(),pageResult.getPageSize());
        QueryWrapper queryWrapper =new QueryWrapper();
        Boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag,"title",pageResult.getQuery());
         iPage=itemMapper.selectPage(iPage,queryWrapper);
         long total = iPage.getTotal();
         List<Item> rows = iPage.getRecords();

        return pageResult.setRows(rows).setTotal(total);
    }
@Transactional
    @Override
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }
@Transactional
    @Override
    public void deleteItemById(Item item) {
        itemMapper.deleteById(item);
        itemDescMapper.deleteById(item.getId());
    }

    /**
     * 实现商品新增  Item/ItemDesc  要求ID相同 一一对应.
     * Item主键自增: 只有执行了insert 入库操作之后才会动态分配ID
     * 难点: itemDesc入库时主键为null
     * 解决方案: 实现主键自动回显功能!!!!
     * @param itemVO
     */
    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        Item item = itemVO.getItem();
        item.setStatus(true);   //默认启用状态
        itemMapper.insert(item);
        itemMapper.insert(item);//MP自动的实现了主键自动回显
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId(item.getId());//MP回显之后取值操作
        itemDescMapper.insert(itemDesc);
    }
}
